package com.coszero.utils.device

import android.annotation.TargetApi
import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Build
import android.util.DisplayMetrics
import android.util.Log
import android.view.ViewConfiguration
import android.view.WindowManager
import java.lang.reflect.Method
import kotlin.math.pow
import kotlin.math.sqrt

/**
 * 获取手机屏幕信息
 * Created by yue on 2016-05-29.
 *
 * @author xmqian
 * @version 1
 */
object DeviceScreenInfoUtils {
    private val TAG: String = "DeviceScreenInfo"

    /**
     * 打印屏幕信息
     *
     * @param context con
     */
    fun printScreenInfo(context: Context) {
        val wm: WindowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val dm: DisplayMetrics = DisplayMetrics()
        wm.getDefaultDisplay().getMetrics(dm)
        val width: Int = dm.widthPixels // 屏幕宽度（像素）
        val height: Int = dm.heightPixels // 屏幕高度（像素）
        val density: Float = dm.density // 屏幕密度（0.75 / 1.0 / 1.5）
        val densityDpi: Int = dm.densityDpi // 屏幕密度dpi（120 / 160 / 240）
        // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        val screenWidth: Int = (width / density).toInt() // 屏幕宽度(dp)
        val screenHeight: Int = (height / density).toInt() // 屏幕高度(dp)
        val xdpi: Float = dm.xdpi //横向坐标
        val ydpi: Float = dm.ydpi //纵向坐标
        //计算屏幕的物理尺寸
        val deviceWidth: Double = (width / xdpi).pow(2.0)
        val deviceHeight: Double = (height / ydpi).pow(2.0)

        Log.i(TAG, "########## 屏幕信息 #########")
        Log.i("h_bl", "屏幕宽度（像素）：" + width)
        Log.i("h_bl", "屏幕高度（像素）：" + height)
        Log.i("h_bl", "屏幕密度（0.75 / 1.0 / 1.5）：" + density)
        Log.i("h_bl", "屏幕密度dpi（120 / 160 / 240）：" + densityDpi)
        Log.i("h_bl", "屏幕宽度（dp）：" + screenWidth)
        Log.i("h_bl", "屏幕高度（dp）：" + screenHeight)
        Log.i(TAG, "屏幕横向最大坐标：" + xdpi)
        Log.i(TAG, "屏幕纵向最大坐标：" + ydpi)
        Log.i(TAG, "屏幕物理宽度()：" + deviceWidth)
        Log.i(TAG, "屏幕物理高度()：" + deviceHeight)
        Log.i(TAG, "屏幕物理尺寸：" + sqrt(deviceWidth + deviceHeight) as Float)
    }

    /**
     * 返回屏幕宽度
     *
     * @param context
     * @return
     */
    @JvmStatic
    fun getScreenWidth(context: Context): Int {
        val displayMetrics: DisplayMetrics = DisplayMetrics()
        val wm: WindowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        wm.getDefaultDisplay().getMetrics(displayMetrics)
        return displayMetrics.widthPixels
    }

    /**
     * 返回当前屏幕是否为竖屏。
     *
     * @param context
     * @return 当且仅当当前屏幕为竖屏时返回true, 否则返回false。
     */
    fun isScreenOriatationPortrait(context: Context): Boolean {
        return context.getResources()
            .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
    }

    /**
     * 获取手机状态栏高度
     *
     * @param context
     * @return
     */
    fun getStatusBarHeight(context: Context): Int {
        var result: Int = 0
        val resourceId: Int =
            context.getResources().getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId)
        }
        return result
    }

    /**
     * 返回屏幕高度
     */
    fun getScreenHeight(context: Context): Int {
        val displayMetrics: DisplayMetrics = DisplayMetrics()
        val wm: WindowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        wm.getDefaultDisplay().getMetrics(displayMetrics)
        return displayMetrics.heightPixels
    }

    /**
     * 获取手机屏幕密度
     */
    fun getDensity(context: Context): Float {
        val dm: DisplayMetrics = context.getResources().getDisplayMetrics()
        return dm.density
    }


    /**
     * 获取虚拟按键的高度
     * android 5.0以后系统拥有的虚拟的返回、桌面、菜单按键
     *
     * @param context
     * @return
     */
    fun getNavigationBarHeight(context: Context): Int {
        var result: Int = 0
        if (hasNavBar(context)) {
            val res: Resources = context.getResources()
            val resourceId: Int = res.getIdentifier("navigation_bar_height", "dimen", "android")
            if (resourceId > 0) {
                result = res.getDimensionPixelSize(resourceId)
            }
        }
        return result
    }

    /**
     * 检查是否存在虚拟按键栏
     *
     * @param context
     * @return
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private fun hasNavBar(context: Context): Boolean {
        val res: Resources = context.getResources()
        val resourceId: Int = res.getIdentifier("config_showNavigationBar", "bool", "android")
        if (resourceId != 0) {
            var hasNav: Boolean = res.getBoolean(resourceId)
            // check override flag
            val sNavBarOverride: String? = navBarOverride
            if ("1" == sNavBarOverride) {
                hasNav = false
            } else if ("0" == sNavBarOverride) {
                hasNav = true
            }
            return hasNav
        } else { // fallback
            return !ViewConfiguration.get(context).hasPermanentMenuKey()
        }
    }

    private val navBarOverride: String?
        /**
         * 判断虚拟按键栏是否重写
         *
         * @return
         */
        get() {
            var sNavBarOverride: String? = null
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                try {
                    val c: Class<*> =
                        Class.forName("android.os.SystemProperties")
                    val m: Method =
                        c.getDeclaredMethod("get", String::class.java)
                    m.setAccessible(true)
                    sNavBarOverride = m.invoke(null, "qemu.hw.mainkeys") as String?
                } catch (e: Throwable) {
                }
            }
            return sNavBarOverride
        }
}
